<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace app\adminapi\controller\v2;

use app\model\admin\TeacherCertModel;
use app\model\admin\TeacherModel;
use app\Request;
use app\adminapi\controller\AuthController;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Filesystem;

class Teacher extends AuthController
{
    public function list()
    {
        $limit = input('size', 10);
        $page = input('page', 1);
        $name = input('teacher', '');
        $idCard = input('idCard', '');
        $number = input('number', '');

        $where = [];
        if ($name) {
            $where[] = ['username', 'like', '%' . $name . '%'];
        }
        if ($idCard) {
            $where[] = ['idcard', 'like', '%' . $idCard . '%'];
        }
        if ($number) {
            $ids = TeacherCertModel::where('cert_code', 'like', '%' . $number . '%')
                ->column('teacher_id');
            $where[] = ['id', 'in', $ids];
        }

        $data = TeacherModel::where('status', 1)
            ->where($where)
            ->with('company')
            ->paginate($limit);

        return app('json')->success([
            'list' => $data->items(),
            'total' => $data->total()
        ]);
    }

    public function save(Request $request)
    {
        $data = $request->only([
            'username', 'idcard', 'mobile', 'idcard_img', 'idcard_img2', 'graduation_img',
            'degree_img'
        ]);
        $certs = input('certs', []);
        $id = input('id', '');
        try {
            validate([
                'username|姓名' => 'require|max:15',
                'idcard|身份证号' => 'idCard',
                'mobile|手机号' => 'mobile',
                'idcard_img|身份证正面' => 'max:255',
                'idcard_img2|身份证反面' => 'max:255',
                'graduation_img|毕业证书' => 'max:255',
                'degree_img|学位证' => 'max:255'
            ])->check($data);
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }
        foreach ($certs as $key => $cert) {
            try {
                validate([
                    'type_id|资质类型' => 'require',
                    'cert_code|职业证书编号' => 'require',
                    'expire_type|是否永久有效' => 'require|in:1,2',
                    'time|证书有效期' => 'requireIf:expire_type,2',
                    'cert_imgs|证书照片' => 'require',
                ])->check($cert);
                if ($cert['expire_type'] == 1) {
                    $cert['expire_time'] = null;
                    $cert['expire_type'] = null;
                } else {
                    $certs[$key]['start_time'] = strtotime($cert['time'][0]);
                    $certs[$key]['end_time'] = strtotime($cert['time'][1]);
                }
                unset($certs[$key]['time']);
            } catch (ValidateException $e) {
                return app('json')->fail($e->getError());
            }
        }
        if ($id) {
            $data['create_time'] = time();
            $res = TeacherModel::where('id', $id)
                ->update($data);
        } else {
            $data['update_time'] = time();
            $id = Db::table('sj_teacher')->insert($data);
        }
        Db::table('sj_teacher_cert')->where('teacher_id', $id)->delete();
        if ($certs && is_array($certs) && count($certs) > 0) {
            foreach ($certs as $key => $cert) {
                $certs[$key]['teacher_id'] = $id;
            }
            Db::table('sj_teacher_cert')
                ->insertAll($certs);
        }
        return app('json')->success();
    }

    public function info()
    {
        $id = input('id', '');
        if ($id) {
            $data = Db::table('sj_teacher')
                ->where('id', $id)
                ->where('status', 1)
                ->find();
            $data['certs'] = Db::table('sj_teacher_cert')
                ->where('teacher_id', $id)
                ->where('status', 1)
                ->select()
                ->toArray();
            foreach ($data['certs'] as $key => $cert) {
                if ($cert['expire_type'] == 2) {
                    $data['certs'][$key]['time'] = [date('Y-m-d', $cert['start_time']), date('Y-m-d', $cert['end_time'])];
                } else {
                    $data['certs'][$key]['time'] = [];
                }
            }
        } else {
            $data = [];
        }
        return app('json')->success([
            'data' => $data,
            'types' => DataType::getCertType(),
        ]);
    }

    public function delete()
    {
        $id = input('id', '');
        $data = Db::name('teacher')
            ->where('id', $id)
            ->where('status', 1)
            ->find();
        if (!$data) {
            return app('json')->fail('数据不存在');
        } else {
            Db::name('teacher')
                ->where('id', $id)
                ->update([
                    'status' => -1,
                    'update_time' => time(),
                ]);
        }
        return app('json')->success();
    }

    public function upload(Request $request)
    {
        $file = $request->file('file');
        $res = Filesystem::disk('public')->putFile('admin', $file);
        return app('json')->success([
            'path' => '/upload/' . $res,
            'url' => request()->domain() . '/upload/' . $res,
        ]);
    }
}
